package com.liuqi.voicenotes

import java.time.DayOfWeek
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.WeekFields
import java.util.Locale

fun formatMillisPretty(millis: Long): String {
    val zone = ZoneId.systemDefault()
    val dt = Instant.ofEpochMilli(millis).atZone(zone)
    val locale = Locale.getDefault()
    val dow = when (dt.dayOfWeek) {
        DayOfWeek.MONDAY -> if (locale.language.startsWith("zh")) "周一" else "Mon"
        DayOfWeek.TUESDAY -> if (locale.language.startsWith("zh")) "周二" else "Tue"
        DayOfWeek.WEDNESDAY -> if (locale.language.startsWith("zh")) "周三" else "Wed"
        DayOfWeek.THURSDAY -> if (locale.language.startsWith("zh")) "周四" else "Thu"
        DayOfWeek.FRIDAY -> if (locale.language.startsWith("zh")) "周五" else "Fri"
        DayOfWeek.SATURDAY -> if (locale.language.startsWith("zh")) "周六" else "Sat"
        DayOfWeek.SUNDAY -> if (locale.language.startsWith("zh")) "周日" else "Sun"
    }
    val hour = dt.hour
    val period = if (locale.language.startsWith("zh")) {
        when {
            hour < 6 -> "凌晨"
            hour < 12 -> "上午"
            hour == 12 -> "中午"
            hour < 18 -> "下午"
            else -> "晚上"
        }
    } else {
        when {
            hour < 6 -> "Early"
            hour < 12 -> "Morning"
            hour == 12 -> "Noon"
            hour < 18 -> "Afternoon"
            else -> "Evening"
        }
    }
    val datePart = if (locale.language.startsWith("zh")) {
        val today = LocalDate.now(zone)
        val localDate = dt.toLocalDate()
        val prefix = when {
            localDate == today -> "今天"
            localDate == today.plusDays(1) -> "明天"
            else -> null
        }
        val base = "${dt.year}年${dt.monthValue}月${dt.dayOfMonth}日"
        prefix?.let { "$it $dow" } ?: "$base $dow"
    } else {
        val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
        "${dt.toLocalDate().format(formatter)} $dow"
    }
    val timePart = String.format(locale, "%02d:%02d", dt.hour, dt.minute)
    return "$datePart $period $timePart"
}

fun isToday(millis: Long): Boolean {
    val zone = ZoneId.systemDefault()
    val d = Instant.ofEpochMilli(millis).atZone(zone).toLocalDate()
    return d == LocalDate.now(zone)
}

fun isThisWeek(millis: Long): Boolean {
    val zone = ZoneId.systemDefault()
    val weekFields = WeekFields.of(Locale.getDefault())
    val d = Instant.ofEpochMilli(millis).atZone(zone).toLocalDate()
    val now = LocalDate.now(zone)
    val w1 = d.get(weekFields.weekOfWeekBasedYear())
    val y1 = d.get(weekFields.weekBasedYear())
    val w2 = now.get(weekFields.weekOfWeekBasedYear())
    val y2 = now.get(weekFields.weekBasedYear())
    return y1 == y2 && w1 == w2
}